<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(C卷,200分)- 连续出牌数量（Java & JS & Python & C）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>有这么一款单人卡牌游戏&#xff0c;牌面由颜色和数字组成&#xff0c;颜色为红、黄、蓝、绿中的一种&#xff0c;数字为0-9中的一个。游戏开始时玩家从手牌中选取一张卡牌打出&#xff0c;接下来如果玩家手中有和他上一次打出的手牌颜色或者数字相同的手牌&#xff0c;他可以继续将该手牌打出&#xff0c;直至手牌打光或者没有符合条件可以继续打出的手牌。</p> 
<p>现给定一副手牌&#xff0c;请找到最优的出牌策略&#xff0c;使打出的手牌最多。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>输入为两行</p> 
<ul><li>第一行是每张手牌的数字&#xff0c;数字由空格分隔&#xff0c;</li><li>第二行为对应的每张手牌的颜色&#xff0c;用r y b g这4个字母分别代表4种颜色&#xff0c;字母也由空格分隔。</li></ul> 
<p>手牌数量不超过10。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>输出一个数字&#xff0c;即最多能打出的手牌的数量。</p> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:63px;">输入</td><td style="width:435px;">1 4 3 4 5<br /> r y b b r</td></tr><tr><td style="width:63px;">输出</td><td style="width:435px;">3</td></tr><tr><td style="width:63px;">说明</td><td style="width:435px;"> <p>如果打&#xff08;1, r&#xff09;-&gt; (5, r)&#xff0c;那么能打两张。</p> <p>如果打&#xff08;4&#xff0c;y) -&gt; (4, b) -&gt; (3, b)&#xff0c;那么能打三张。</p> </td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:64px;">输入</td><td style="width:434px;">1 2 3 4<br /> r y b l</td></tr><tr><td style="width:64px;">输出</td><td style="width:434px;">1</td></tr><tr><td style="width:64px;">说明</td><td style="width:434px;">没有能够连续出牌的组合&#xff0c;只能在开始时打出一张手牌&#xff0c;故输出1</td></tr></tbody></table> 
<p></p> 
<h4>题目解析</h4> 
<p>本题连续出牌的条件是&#xff1a;</p> 
<blockquote> 
 <p>如果玩家手中有和他上一次打出的手牌颜色或者数字相同的手牌&#xff0c;他可以继续将该手牌打出</p> 
</blockquote> 
<p>因此&#xff0c;我们可以基于回溯算法&#xff0c;来求解不同的出牌方式&#xff0c;而下张牌是否可出的条件是&#xff1a;</p> 
<ul><li>和上一张牌的数字相同&#xff0c;或者和上一张牌的颜色相同</li></ul> 
<p></p> 
<h4>JS算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 2) {
    const nums &#61; lines[0].split(&#34; &#34;);
    const colors &#61; lines[1].split(&#34; &#34;);

    console.log(getMaxCount(nums, colors));

    lines.length &#61; 0;
  }
});

class Card {
  constructor(num, color) {
    this.num &#61; num;
    this.color &#61; color;
  }
}

function getMaxCount(nums, colors) {
  const n &#61; nums.length;

  const cards &#61; [];
  for (let i &#61; 0; i &lt; n; i&#43;&#43;) {
    cards[i] &#61; new Card(nums[i], colors[i]);
  }

  const ans &#61; [0];
  const used &#61; new Array(n).fill(false);

  dfs(cards, used, undefined, 0, ans);
  return ans[0];
}

function dfs(cards, used, last, count, ans) {
  ans[0] &#61; Math.max(ans[0], count);

  for (let i &#61; 0; i &lt; cards.length; i&#43;&#43;) {
    if (used[i]) continue;

    const cur &#61; cards[i];
    if (last &amp;&amp; last.num !&#61; cur.num &amp;&amp; last.color !&#61; cur.color) continue;

    used[i] &#61; true;
    dfs(cards, used, cur, count &#43; 1, ans);
    used[i] &#61; false;
  }
}
</code></pre> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.Arrays;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    int[] nums &#61; Arrays.stream(sc.nextLine().split(&#34; &#34;)).mapToInt(Integer::parseInt).toArray();
    String[] colors &#61; sc.nextLine().split(&#34; &#34;);

    System.out.println(getResult(nums, colors));
  }

  static class Card {
    int num;
    char color;

    public Card(int num, String color) {
      this.num &#61; num;
      this.color &#61; color.charAt(0);
    }
  }

  public static int getResult(int[] nums, String[] colors) {
    int n &#61; nums.length;
    Card[] cards &#61; new Card[n];
    for (int i &#61; 0; i &lt; n; i&#43;&#43;) cards[i] &#61; new Card(nums[i], colors[i]);

    int[] ans &#61; {0};
    boolean[] used &#61; new boolean[n];
    dfs(cards, used, null, 0, ans);
    return ans[0];
  }

  public static void dfs(Card[] cards, boolean[] used, Card last, int count, int[] ans) {
    ans[0] &#61; Math.max(ans[0], count);

    for (int i &#61; 0; i &lt; cards.length; i&#43;&#43;) {
      if (used[i]) continue;

      Card cur &#61; cards[i];
      if (last !&#61; null &amp;&amp; last.num !&#61; cur.num &amp;&amp; last.color !&#61; cur.color) continue;

      used[i] &#61; true;
      dfs(cards, used, cur, count &#43; 1, ans);
      used[i] &#61; false;
    }
  }
}
</code></pre> 
<h4 style="background-color:transparent;">Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
nums &#61; input().split()
colors &#61; input().split()


def dfs(cards, used, last, count, ans):
    ans[0] &#61; max(ans[0], count)

    for i in range(len(cards)):
        if used[i]:
            continue

        cur &#61; cards[i]
        if last and last.num !&#61; cur.num and last.color !&#61; cur.color:
            continue

        used[i] &#61; True
        dfs(cards, used, cur, count &#43; 1, ans)
        used[i] &#61; False


class Card:
    def __init__(self, num, color):
        self.num &#61; num
        self.color &#61; color


# 算法入口
def getResult():
    n &#61; len(nums)

    cards &#61; [Card(nums[i], colors[i]) for i in range(n)]

    ans &#61; [0]
    used &#61; [False] * n

    dfs(cards, used, None, 0, ans)

    return ans[0]


# 算法调用
print(getResult())
</code></pre> 
<h4>C算法源码</h4> 
<pre><code class="language-cpp">#include &lt;stdio.h&gt;

#define MAX(a,b) ((a) &gt; (b) ? (a) : (b))

#define MAX_SIZE 10

typedef struct {
    int num;
    char color;
} Card;

// 记录题解
int ans &#61; 0;

// 记录输入的卡牌信息
Card cards[MAX_SIZE];
int cards_size &#61; 0;

// 回溯求解所有出牌情况
void dfs(int used[], Card* last, int count);

int main() {
    while (scanf(&#34;%d&#34;, &amp;cards[cards_size].num)) {
        cards_size&#43;&#43;;
        if (getchar() !&#61; &#39; &#39;) break;
    }

    for (int i &#61; 0; i &lt; cards_size; i&#43;&#43;) {
        cards[i].color &#61; (char) getchar();
        getchar();
    }

    // 记录哪些牌使用过了
    int used[MAX_SIZE] &#61; {0};
    dfs(used, NULL, 0);

    printf(&#34;%d\n&#34;, ans);

    return 0;
}

void dfs(int used[], Card* last, int count) {
    ans &#61; MAX(ans, count);

    for(int i&#61;0; i&lt;cards_size; i&#43;&#43;) {
        // 如果当前牌已经使用过&#xff0c;则不能出牌
        if(used[i]) continue;

        // 当前牌
        Card cur &#61; cards[i];

        // 如果 和上一张牌的数字不同&#xff0c;且和上一张牌的颜色也不同&#xff0c;则不能出牌
        if(last !&#61; NULL &amp;&amp; last-&gt;num !&#61; cur.num &amp;&amp; last-&gt;color !&#61; cur.color) continue;

        used[i] &#61; 1;
        dfs(used, &amp;cur, count &#43; 1);
        used[i] &#61; 0;
    }
}</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>